package org.dja.nzw.discovery;

import org.dja.nzw.discovery.zookeeper.ZKDiscoveryClient;

import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by shuyun on 2016/7/18.
 */
public class DiscoveryManager {
    private static final AtomicReference<DiscoveryClient> discoveryClient = new AtomicReference<DiscoveryClient>();

    synchronized public static final DiscoveryClient create(String serverUrl) throws InterruptedException {
        if(null != discoveryClient.get()) {
            return discoveryClient.get();
        }

        discoveryClient.set(new ZKDiscoveryClient(serverUrl));
        discoveryClient.get().startup();
        return discoveryClient.get();
    }

    synchronized public static final void destory()throws InterruptedException {
        DiscoveryClient client = discoveryClient.getAndSet(null);
        if(null != client) {
            client.shutdown();
        }
    }

    public static final DiscoveryClient getClient() {
        if (discoveryClient.get() == null) {
            throw new IllegalStateException("discovery client is not created");
        }
        return discoveryClient.get();
    }
}
